package org.huang.sample12.controller;

import org.huang.sample12.exception.BaseException;
import org.huang.sample12.exception.MyException1;
import org.huang.sample12.exception.MyException2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.io.IOException;

@RestController
@Validated
public class DemoController {
    private Logger logger = LoggerFactory.getLogger("DemoController");

    @RequestMapping("/ex1")
    public Object throwBaseException() throws Exception {
        throw new BaseException("This is BaseException.");
    }

    @RequestMapping("/ex2")
    public Object throwMyException1() throws Exception {
        throw new MyException1("This is MyException1.");
    }

    @RequestMapping("/ex3")
    public Object throwMyException2() throws Exception {
        throw new MyException2("This is MyException2.");
    }

    @RequestMapping("/ex4")
    public Object throwIOException() throws Exception {
        throw new IOException("This is IOException.");
    }

    @RequestMapping("/ex5")
    public Object throwNullPointerException() throws Exception {
        throw new NullPointerException("This is NullPointerException.");
    }

    @RequestMapping("/ex6")
    public Object validationException(@NotNull(message = "name不能为null") String name){
        System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxx");
        return "";
    }



    //因为我们在 DemoController 中使用 ExceptionHandler 注解定义了一个 Controller 级的异常处理器,
    // 这个级别的异常处理器的优先级比全局的异常处理器优先级高, 因此 Spring 发现 controllerExceptionHandler 可以处理 NullPointerException 异常时,
    // 就调用这个方法, 而不会调用全局的 defaultErrorHandler 方法了.
    @ExceptionHandler(NullPointerException.class)
    public String controllerExceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("---ControllerException Handler---Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), e.getMessage());
        return e.getMessage();
    }

}